package speed2010.andreza.vspeed.util;

import java.io.IOException;
import java.util.Properties;

/**
 * @author <a href="mailto:andreza.lba@gmail.com">Andreza Leite de Alencar</a>
 */
public final class PropertiesUtils {

	private PropertiesUtils() {
	}

	public static final String PREFIX = "vspeed.";
	private static Properties props;

	static {
		props = new Properties();
		props.putAll(System.getProperties());
	}

	public static void loadProperties(final String file) {
		try {
			props.putAll(readPropertiesFile(file));
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}

	public static void putProperty(final String key, final String value) {
		if (key == null) {
			return;
		}

		String realKey = key;
		if (!key.startsWith(PREFIX)) {
			realKey = PREFIX + key;
		}

		props.put(realKey, value);
	}

	public static String getProperty(final String key) {
		return getProperty(key, null);
	}

	public static String getProperty(final String key, final String defaultValue) {
		if (key == null) {
			return null;
		}

		String realKey = key;
		if (!key.startsWith(PREFIX)) {
			realKey = PREFIX + key;
		}

		final String property = props.getProperty(realKey, defaultValue);
		
		return property;
	}

	private static Properties readPropertiesFile(final String file) throws IOException {
		final Properties properties = new Properties();
		properties.load(SerializationUtils.createStream(file));

		return properties;
	}

}
